package com.yingu.bookmanage_ssm1.Controller;

import java.util.List;
import java.util.Map;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.yingu.bookmanage_ssm1.Pojo.BookPojo;
import com.yingu.bookmanage_ssm1.Services.BookServiceImpl;

@Controller
@RequestMapping(value="/book")
public class BookController {

	@Autowired
	BookServiceImpl bsi;
	
	
	@RequestMapping(value="/findAll")
	public String findAll(@RequestParam(value="indexPage",defaultValue="1") Integer indexPage,@RequestParam(value="pageSize",defaultValue="5") Integer pageSize,Map<String,Object> map){
		if(indexPage<1){
			indexPage=1;
		}
		
		if(pageSize<1){
			pageSize=1;
		}
		
		int count = bsi.count();
		
		int countPage = bsi.countPage(pageSize);
		
		if(indexPage>countPage){
			indexPage=countPage;
		}
		
		if(pageSize>count){
			pageSize=count;
		}
		
		
		
		List<BookPojo>  list = bsi.findAll(indexPage, pageSize);
		
		map.put("indexPage",indexPage);
		
		map.put("pageSize",pageSize);
		
		map.put("count",count);
		
		map.put("countPage",countPage);
		
		map.put("list",list);
		
		
		return "index";
	}
	
	@RequestMapping(value="delete")
	public String delete(@RequestParam(value="id") Integer id,Map<String,Object> map){
		boolean a = bsi.delete(id);
		if(a){
			map.put("flag",1);
		}else{
			map.put("flag",2);
		}
		return "index";
	}
	
	@RequestMapping(value="findById")
	public String findById(@RequestParam Integer id,Map<String,Object> map){
		BookPojo bp = bsi.findById(id);
		map.put("info", bp);
		return "forward:/updateBook.jsp";
	}
	
	@RequestMapping(value="add")
	public String addBook(BookPojo bp,Map<String,Object> map){
		boolean a = bsi.addBook(bp);
		if(a){
			map.put("flag1",1);
		}else{
			map.put("flag1",2);
		}
		return "index";
	}
	
	@RequestMapping(value="update")
	public String updateBook(BookPojo bp,Map<String,Object> map){
		boolean a = bsi.updateBook(bp);
		if(a){
			map.put("flag2",1);
		}else{
			map.put("flag2",2);
		}
		return "index";
	}
}
